﻿using PermissionDesign.Model.Entity;
using PermissionDesign.Model.Response;
using PermissionDesign.Tool;
using System;
using System.Linq;
using System.Linq.Expressions;

namespace PermissionDesign.Service
{
    public class LoginService : BaseService
    {
        //继承父类中有参构造函数
        public LoginService(DataContext dbContext) : base(dbContext)
        {
            _dbContext = dbContext;
        }

        #region 查询用户是否存在
        public bool IsUserExist(Expression<Func<User, bool>> where)
        {
            return _dbContext.User.FirstOrDefault(where) != null;
        }
        #endregion

        #region 登录
        public ResponseModel Login(string account, string passwd)
        {
            var loginUser = _dbContext.User.FirstOrDefault(c => c.LoginAccount == account);
            if (loginUser == null)
            {
                return new ResponseModel { code = 0, result = "用户不存在" };
            }

            if (loginUser.IsEnabled == 0)
            {
                return new ResponseModel { code = 0, result = "用户已被禁用" };
            }
            else
            {
                string pass = PassHelper.SingleTon().EncryptByMd5(loginUser.LoginKey + passwd);
                if (pass == loginUser.LoginPassword)
                {
                    return new ResponseModel
                    {
                        code = 200,
                        data = new Response_User
                        {
                            Id = loginUser.Id,
                            RoleId = (int)loginUser.RoleId,
                            Name = loginUser.Name,
                            LoginAccount = loginUser.LoginAccount,
                            IsEnabled = loginUser.IsEnabled
                        }
                    };
                }
                return new ResponseModel { code = 0, result = "密码错误" };
            }
        }
        #endregion

    }
}
